import time

from pyrfid.DataProtocol.Exception.ExecutionCodeException.InterrogatorCommunicationErrorException import InterrogatorCommunicationErrorException
from pyrfid.DataProtocol.Driver.DataManager import DataManager
from pyrfid.DataProtocol.Driver.VirtualTag.VirtualUHFTag import VirtualUHFTag
from pyrfid.DataProtocol.Driver.VirtualTag import VirtualTag, VirtualHFTag
from pyrfid.DataProtocol.Driver.DriverInterface import DriverInterface
from pyrfid.DataProtocol.Driver.DriverException.SessionInValidException import SessionInValidException

class SessionManager(object):
    
    __driver = object
    __sessionList = dict()
    __dataManager = object
    __virtualTag = object
    __life_time = int()
    __tagIdAndSession = dict()
    __handleValue = str()
    __LEVEL = 0
    __virtual_tag = ""
    
    __has_virtual_tag_list = dict()
    __has_handle_value = dict()
    __has_create_time = dict()    
    
    def __init__(self, life_time):
        self.__life_time = life_time
    
    def getVirtualTag(self, tag_id, virtual_tag_type):
        
        if self.__has_create_time.has_key(tag_id) == False:
            raise SessionInValidException
        
        if time.clock() - self.__has_create_time[tag_id] > self.__life_time:
            raise SessionInValidException

        if self.__has_virtual_tag_list.has_key(tag_id) == True:
            return self.__has_virtual_tag_list[tag_id]
                
        if virtual_tag_type == DriverInterface.UHF_VIRTUAL_TAG_TYPE:
            self.__has_virtual_tag_list[tag_id] = VirtualUHFTag(tag_id)
        elif virtual_tag_type == DriverInterface.HF_VIRTUAL_TAG_TYPE:
            self.__has_virtual_tag_list[tag_id] = VirtualHFTag(tag_id)
        else:
            raise "ERROR"    
        
        return self.__has_virtual_tag_list[tag_id]
                
    def setSession(self, tag_id,  handle_value, create_time):
        print "new Session"        
        self.__has_handle_value[tag_id] = handle_value
        self.__has_create_time[tag_id] = create_time
        
        
    def getSession(self, tag_id):        
        print "get Session"
        if self.__has_create_time.has_key(tag_id) == False:
            raise InterrogatorCommunicationErrorException
        
        print self.__has_create_time
        if self.__has_create_time[tag_id] == 0:
            raise SessionInValidException
        
        if time.clock() - self.__has_create_time[tag_id] > self.__life_time:
            raise InterrogatorCommunicationErrorException
        
        return self.__has_handle_value[tag_id]
    